<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <el-form :model="formdata"
               label-position="right"
               ref="formdataRef"
               label-width="150px"
               :rules='formdataRules'>
        <el-form-item label="服务名称："
                      prop="remoteEcgProductDto.name">
          <el-input placeholder="请输入服务名称"
                    maxlength="20"
                    show-word-limit
                    v-model="formdata.remoteEcgProductDto.name"
                    clearable
                    class="w-200"></el-input>
        </el-form-item>
        <el-form-item label="所属医院："
                      prop="remoteEcgProductDto.hospitalId">
          <el-select v-model="formdata.remoteEcgProductDto.hospitalId"
                     clearable
                     class="w-200"
                     placeholder="请选择所属医院">
            <el-option v-for="item in hospitalList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用人群："
                      prop="remoteEcgProductDto.users">
          <el-input placeholder="请输入适用人群"
                    v-model="formdata.remoteEcgProductDto.users"
                    class="w-200"></el-input>
        </el-form-item>
        <el-form-item label="服务选项：">
          <el-button type="primary"
                     @click="handleService('add', null, null)">新 增</el-button>
          <el-table border
                    :data="formdata.remoteEcgSkuList"
                    class="mt-20"
                    style="width:80%">
            <el-table-column label="价格（元）">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.price"
                                 :min="0"
                                 placeholder="请输入价格"
                                 :controls="true"
                                 class="w-200"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="检测时长（小时）">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.monitoringDuration"
                                 :min="0"
                                 placeholder="请输入检测时长"
                                 :controls="true"
                                 class="w-200"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="推广分成（元）">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.share"
                                 :min="0"
                                 placeholder="请输入推广分成费用"
                                 :controls="true"
                                 class="w-200"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           @click="handleService('add', null, null)">新 增</el-button>
                <el-button type="danger"
                           @click="handleService('del', formdata.remoteEcgSkuList, scope.$index)">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="有效期："
                      prop="remoteEcgProductDto.termOfValidity">
          <el-input-number v-model="formdata.remoteEcgProductDto.termOfValidity"
                           :min="0"
                           placeholder="请输入有效期"
                           :controls="true"
                           class="w-200"></el-input-number>
          <span class="unit">天</span>
        </el-form-item>
        <el-form-item label="列表图片："
                      prop="remoteEcgProductDto.listImgUrl">
          <el-upload class="avatar-uploader"
                     :action="imageUploadUrl"
                     :show-file-list="false"
                     accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="formdata.remoteEcgProductDto.listImgUrl"
                 :src="formdata.remoteEcgProductDto.listImgUrl"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情图片："
                      prop="remoteEcgProductDto.detailImgUrl">
          <el-upload multiple
                     :limit=limitImgNum
                     :action="imageUploadUrl"
                     accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                     list-type="picture-card"
                     :on-success="handlePictureCardPreview"
                     :file-list='formdata.remoteEcgProductDto.detailImg'
                     :on-exceed='onexceed'
                     :on-remove='onremove'
                     :before-upload="beforeAvatarUpload">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="温馨提示："
                      prop="remoteEcgProductDto.reminder">
          <el-input v-model="formdata.remoteEcgProductDto.reminder"
                    :min="0"
                    placeholder="请输入温馨提示"
                    type="textarea"
                    style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="标配服务："
                      prop="remoteEcgProductDto.standardService">
          <el-input v-model="formdata.remoteEcgProductDto.standardService"
                    :min="0"
                    placeholder="请输入标配服务"
                    type="textarea"
                    style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="可适用的健康风险筛查与监测范围："
                      prop="remoteEcgProductDto.monitoringScope">
          <el-input v-model="formdata.remoteEcgProductDto.monitoringScope"
                    :min="0"
                    placeholder="请输入可适用的健康风险筛查与监测范围"
                    type="textarea"
                    style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="特别说明："
                      prop="remoteEcgProductDto.specialNotes">
          <el-input v-model="formdata.remoteEcgProductDto.specialNotes"
                    :min="0"
                    placeholder="请输入特别说明"
                    type="textarea"
                    style="width:50%"></el-input>
        </el-form-item>
        <el-form-item label="医学知识：">
          <el-button type="success"
                     @click="handleAddRow(1)">新 增 一 项</el-button>
          <el-table :data="formdata.remoteMedicalKnowledgeDtoList"
                    class="mt-20"
                    border
                    show-header>
            <el-table-column label="项目名称">
              <template slot-scope="scoped">
                <el-form-item :rules="listRules.name"
                              :prop="'remoteMedicalKnowledgeDtoList.' + scoped.$index + '.name'">
                  <el-input v-model="scoped.row.name"
                            maxlength="50"
                            autocomplete="off"
                            class="w-200"
                            placeholder="请输入项目名称"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="clinicalSignificance"
                             label="临床意义">
              <template slot-scope="scoped">
                <el-form-item :rules="listRules.clinicalSignificance"
                              :prop="'remoteMedicalKnowledgeDtoList.' + scoped.$index + '.clinicalSignificance'">
                  <el-input v-model="scoped.row.clinicalSignificance"
                            maxlength="500"
                            :rows="4"
                            type="textarea"
                            autocomplete="off"
                            show-word-limit
                            placeholder="请输入临床意义"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address"
                             label="图片"
                             width="150"
                             align="center">
              <template slot-scope="scoped">
                <el-form-item :rules="listRules.knowledgeImgUrl"
                              :prop="'remoteMedicalKnowledgeDtoList.' + scoped.$index + '.knowledgeImgUrl'">
                  <div @click="op(scoped.$index)">
                    <el-upload class="avatar-uploader"
                               :action="imageUploadUrl"
                               :show-file-list="false"
                               accept=".JPG, .PNG, .JPEG,.jpg, .png, .jpeg"
                               :on-success="heartMedicalKnowledgeSuccess"
                               :before-upload="beforeAvatarUpload">
                      <img v-if="scoped.row.knowledgeImgUrl"
                           :src="scoped.row.knowledgeImgUrl"
                           class="avatar">
                      <i v-else
                         class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address"
                             label="操作"
                             width="100">
              <template slot-scope="scoped">
                <el-button type="text"
                           @click='deleteTable(scoped.$index, formdata.remoteMedicalKnowledgeDtoList)'>删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="医学知识链接："
                      prop="remoteMedicalKnowledgeLinkDtoList">
          <el-button type="success"
                     @click="handleAddRow(2)">新 增 一 项</el-button>
          <el-table :data="formdata.remoteMedicalKnowledgeLinkDtoList"
                    class="mt-20"
                    border>
            <el-table-column prop="title"
                             label="链接标题">
              <template slot-scope="scoped">
                <el-form-item :rules="listRules.title"
                              :prop="'remoteMedicalKnowledgeLinkDtoList.' + scoped.$index + '.title'">
                  <el-input v-model="scoped.row.title"
                            maxlength="50"
                            autocomplete="off"
                            placeholder="请输入链接标题"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="link"
                             label="链接">
              <template slot-scope="scoped">
                <el-form-item :rules="listRules.link"
                              :prop="'remoteMedicalKnowledgeLinkDtoList.' + scoped.$index + '.link'">
                  <el-input v-model="scoped.row.link"
                            type="textarea"
                            maxlength="500"
                            :rows="4"
                            autocomplete="off"
                            show-word-limit
                            placeholder="请输入链接"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="address"
                             label="操作"
                             width="100">
              <template slot-scope="scoped">
                <el-button type="text"
                           @click='deleteTable(scoped.$index, formdata.remoteMedicalKnowledgeLinkDtoList)'>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="购买服务后，是否填写健康服务号："
                      label-width="240px">
          <el-radio-group v-model="formdata.remoteEcgProductDto.isInvitationCode">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否支持退款：">
          <el-radio-group v-model="formdata.remoteEcgProductDto.refund">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button @click="modalClose">取 消</el-button>
          <el-button type="primary"
                     @click="onSubmit">保 存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: '', // 胎心解读管理弹窗
    props: {
      ECGObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
      getList: {
        type: Function,
        default: null
      },
      isDetail: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        title: '新 增',
        loading: false,
        limitImgNum: 6,
        formdata: {
          remoteEcgProductDto: {
            id: null,
            name: '',
            hospitalId: '',
            termOfValidity: '', // 有效期
            listImgUrl: '', // 列表图片
            detailImgUrl: [], // 详情图片
            detailImg: [],
            reminder: '', // 温馨提示
            standardService: '', // 标配服务
            monitoringScope: '', // 可适用的健康风险筛查与监测范围
            specialNotes: '', // 特别说明
            refund: 0, // 是否支持退款
            users: '', // 适用人群
            isInvitationCode: 0, // 健康服务号
          },
          remoteEcgSkuList: [{ id: null }], // 服务选项
          remoteMedicalKnowledgeDtoList: [
            {
              id: null,
              name: '',
              knowledgeImgUrl: '', // 医学知识图片
              clinicalSignificance: '', // 临床意义
            }
          ],
          remoteMedicalKnowledgeLinkDtoList: [
            {
              id: null,
              title: '',
              link: '',
            }
          ],
        },
        whichImg: 0,
        // imageUploadUrl: this.api.file.upload,
        imageUploadUrl: this.api.appUpgradeUpload.url,
        formdataRules: {
          'remoteEcgProductDto.name': [
            { required: true, message: '请输入服务名称', trigger: 'blur' }
          ],
          'remoteEcgProductDto.hospitalId': [
            { required: true, message: '请选择所属医院', trigger: ['change', 'blur'] }
          ],
          'remoteEcgProductDto.users': [
            { required: true, message: '请输入适用人群', trigger: 'blur' }
          ],
          'remoteEcgProductDto.termOfValidity': [
            { required: true, message: '请输入有效期', trigger: 'blur' }
          ],
          'remoteEcgProductDto.reminder': [
            { required: true, message: '请输入温馨提示', trigger: 'blur' }
          ],
          'remoteEcgProductDto.specialNotes': [
            { required: true, message: '请输入特别说明', trigger: 'blur' }
          ],
          'remoteEcgProductDto.monitoringScope': [
            { required: true, message: '请输入监测范围', trigger: 'blur' }
          ],
          'remoteEcgProductDto.standardService': [
            { required: true, message: '请输入标配服务', trigger: 'blur' }
          ],
          'remoteEcgProductDto.listImgUrl': [
            { required: true, message: '请上传列表图片', trigger: ['change', 'blur'] }
          ],
          'remoteEcgProductDto.detailImgUrl': [
            { required: true, message: '请上传详情图片', trigger: ['change', 'blur'] }
          ],

        },
        listRules: {
          name: [{ required: true, message: '请输入项目名称', trigger: ['blur', 'change'] }],
          clinicalSignificance: [{ required: true, message: '请输入临床意义', trigger: 'blur' }],
          knowledgeImgUrl: [{ required: true, message: '请上传医学知识图片', trigger: ['blur', 'change'] }],
          title: [{ required: true, message: '请输入链接标题', trigger: 'blur' }],
          link: [{ required: true, message: '请输入链接', trigger: 'blur' }],
        },
        hospitalList: []
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      // 所属医院
      async selectHospital () {
        const { data: res } = await this.post(this.api.hospitalECG.selectRemoteHospitalByName, {
          remoteType: 4,
          hospitalName: '',
          pageIndex: 0,
          pageSize: 100
        })
        if (res.code === '200') {
          this.hospitalList = res.object
        }
      },
      // 动态添加行
      handleAddRow (index) {
        switch (index) {
          case 1:
            this.formdata.remoteMedicalKnowledgeDtoList.push({
              id: null,
              name: '',
              knowledgeImgUrl: '', // 医学知识图片
              clinicalSignificance: '', // 临床意义
            })
            break
          case 2:
            this.formdata.remoteMedicalKnowledgeLinkDtoList.push({
              id: null,
              title: '',
              link: '',
            })
            break
        }
      },
      // 服务选项
      handleService (op, table, index) {
        switch (op) {
          case 'add':
            this.formdata.remoteEcgSkuList.push({
              id: null,
              price: '',
              monitoringDuration: '',
              share: ''
            })
            break;
          case 'del':
            if (table.length == 1) {
              this.$message.warning('至少保留一项')
              return
            } else {
              table.splice(index, 1)
            }
            break;
        }
      },
      op (index) {
        this.whichImg = index
      },
      // 医学知识
      heartMedicalKnowledgeSuccess (res) {
        this.formdata.remoteMedicalKnowledgeDtoList.forEach((ele, index) => {
          if (this.whichImg == index) {
            this.$set(ele, 'knowledgeImgUrl', res.object[0])
          }
        })
      },
      // 列表图片地址
      handleAvatarSuccess (res) {
        this.formdata.remoteEcgProductDto.listImgUrl = res.object[0];
      },
      beforeAvatarUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      // 详情图片地址
      handlePictureCardPreview (res) {
        this.formdata.remoteEcgProductDto.detailImgUrl.push(res.object[0])
      },
      onremove (res, list) {
        if (res.response) {
          this.formdata.remoteEcgProductDto.detailImgUrl = this.formdata.remoteEcgProductDto.detailImgUrl.filter(ele => ele != res.response.object[0])
        } else {
          this.formdata.remoteEcgProductDto.detailImgUrl = this.formdata.remoteEcgProductDto.detailImgUrl.filter(ele => ele != res.url)
        }
      },
      onexceed () {
        this.$message.warning(`详情图片至多上${this.limitImgNum}6张`);
      },
      // 保存
      onSubmit () {
        this.$refs.formdataRef.validate((valid) => {
          if (valid) {
            let { detailImg, ...params } = this.formdata.remoteEcgProductDto
            params.detailImgUrl = JSON.stringify(params.detailImgUrl)
            this.post(this.api.hospitalECG.saveRemoteEcgProduct, {
              remoteEcgSkuList: this.formdata.remoteEcgSkuList,
              remoteMedicalKnowledgeDtoList: this.formdata.remoteMedicalKnowledgeDtoList,
              remoteMedicalKnowledgeLinkDtoList: this.formdata.remoteMedicalKnowledgeLinkDtoList,
              remoteEcgProductDto: params
            }).then(({ data }) => {
              if (data.code === '200') {
                this.modalClose()
                this.$parent.getList() // 调用父件组方法
                this.$message.success('保存成功!')
              } else {
                this.$message.error(data.message)
              }
            })
          }
        })
      },
      // 动态删除数据
      deleteTable (index, table) {
        if (table.length == 1) {
          this.$message.warning('至少保留一项')
          return
        } else {
          table.splice(index, 1)
        }
      },
      // 查询详情
      async getDetail () {
        const { data: res } = await this.post(this.api.hospitalECG.getRemoteEcgProductDetail, {
          id: this.ECGObj.id
        })
        if (res.code === '200') {
          let resData = res.object
          this.formdata.remoteEcgSkuList = resData.remoteEcgSkuList
          this.formdata.remoteEcgProductDto = resData.remoteEcgProductDto
          this.formdata.remoteEcgProductDto.detailImgUrl = JSON.parse(this.formdata.remoteEcgProductDto.detailImgUrl)
          this.formdata.remoteEcgProductDto.detailImg = []
          this.formdata.remoteEcgProductDto.detailImgUrl.forEach(ele => {
            let op = {}
            op.name = ele
            op.url = ele
            this.formdata.remoteEcgProductDto.detailImg.push(op)
          })
          this.formdata.remoteMedicalKnowledgeDtoList = resData.remoteMedicalKnowledgeDtoList
          this.formdata.remoteMedicalKnowledgeLinkDtoList = resData.remoteMedicalKnowledgeLinkDtoList
        }

      }
    },
    created () {
      if (this.ECGObj) {
        this.getDetail() // 查询详情
        this.title = '编 辑'
      }
      this.selectHospital()
    },


  }
</script>
<style scoped lang="scss">
  .el-upload-list--picture-card .el-upload-list__item {
    width: 98px !important;
    height: 98px !important;
  }
  .el-upload--picture-card {
    width: 98px !important;
    height: 98px !important;
    line-height: 98px !important;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 98px !important;
    height: 98px !important;
    line-height: 98px !important;
    text-align: center;
  }
  .avatar {
    width: 98px !important;
    height: 98px !important;
    display: block;
  }
  .unit {
    padding-left: 10px;
  }
</style>